import { useContext, useEffect, useMemo, useState } from 'react';
import { SearchOutlined, EyeOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { TagSelectNew } from '@/components/TagSelectNew';
import { UploadFormCommon } from '@/components/UploadForm';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import {
  getLoadMapList,
  getTenantID,
  getUserDepName,
  getFileNameByPath,
  getUserDepID,
  renderTableTextNotColor,
  getSelectDataMapList,
  getCompanyID,
  getPosIDs,
  getUserID,
  getUserName,
  getUserShortCode,
  getColorTextLoadMap,
  splitFileUrl,
  downloadTemplate,
  getFileNameNotType,
  removeDateHmsStr,
} from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { useDescriptionsType } from '@/components/DescriptionsType';
import { RegularExpression } from '@/common/constVariable';
import moment from 'moment';
import { Form, Input, Slider, Tooltip, TreeSelect, Select, message, Switch, Button } from 'antd';
import MyIcon from '@/components/MyIcon';
import { UpdateMaterielView } from './UpdateMaterielView';
import { UpdateContractView } from './UpdateContractView';
import { AcquisitionManageContext } from '../mconfig/useManageContext';
import { UpdateServiceView } from './UpdateServiceView';
import { getBaseUrl } from '@/services/urlconst';
import { readReadShowFileService } from '@/services/BaseLayout';

const getUpdateConfig = ({
  pageType,
  record,
  openMaterialModalStatus,
  addMaterialModalStatus,
  editTable,
  openServerModalStatus,
  handleApplyPurchase,
  handleSelectContract,
  handleContractProcess,
  contractForm,
  handleChangeBtn,
}) => {
  /** 表单数据 */
  const { contractList } = useContext(AcquisitionManageContext);
  // 判断渲染列表
  const [isShowListType, setIsShowListType] = useState<number>();
  // 是否线下验收
  const [isLineDown, setIsLineDown] = useState<boolean>(false);
  // 是否有合同
  const [isHaveContract, setIsHaveContract] = useState<boolean>(false);

  // 没有合同的情况
  const isNoContract = !contractList.length;

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  useEffect(() => {
    // 回填表单
    contractForm?.setFieldsValue({
      ...record,
      createTime: moment(record?.createTime),
    });
    setIsShowListType(record.storageType);
  }, []);

  const disabled: boolean = pageType === 'detail';

  /** 表单配置 */
  const [config, methods] = useDescriptionsType({
    labelWidth: 190,
    basicForm: contractForm,
    isShowNumTitle: false,
    name: 'accept-addAndEdit',
    schemas: [
      {
        key: 'accept-basic',
        title: '一、基本信息',
        fieldChildren: [
          {
            label: '申请日期',
            field: 'createTime',
            component: 'DatePicker',
            placeholder: '请选择申请日期',
            disabled: disabled,
            required: true,
            disabledDate: (current) => {
              return current && current > moment(new Date(), 'YYYY-MM-DD');
            },
          },
          {
            field: `applyCode`,
            label: `流水单号`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带入',
            required: false,
          },
          {
            field: `createrName`,
            label: `申请人`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createPhone`,
            label: `联系电话`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createDepartmentName`,
            label: `申请部门/单位`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `createPositionName`,
            label: `职务岗位`,
            component: 'Input',
            disabled: true,
            required: false,
            placeholder: '自动带出',
          },
          {
            field: `applyTitle`,
            label: `事项名称`,
            component: 'Input',
            disabled: disabled,
            placeholder: '请输入',
            autoComplete: 'off',
            required: true,
          },
          {
            field: `oto`,
            label: `验收方式`,
            component: 'Render',
            required: true,
            disabled: disabled,
            placeholder: '请选择',
            render: (text) => {
              return (
                <TagSelect
                  colSpan={24}
                  formLabel={''}
                  formName={'oto'}
                  defalultKeys={Number(text)}
                  onChange={(value) => {
                    if (value == 1) {
                      setIsLineDown(true);
                      handleChangeBtn(true);
                    } else {
                      setIsLineDown(false);
                      handleChangeBtn(false);
                    }
                  }}
                  radioDisabled={disabled}
                  radioList={[
                    {
                      value: 0,
                      name: '线上验收',
                    },
                    {
                      value: 1,
                      name: '线下验收',
                    },
                  ]}
                />
              );
            },
          },
          {
            field: `haveContract`,
            label: `是否有合同`,
            component: 'Render',
            required: false,
            colSpan: 2,
            disabled: disabled,
            placeholder: '请选择',
            render: (text: string | number) => {
              return (
                <Switch
                  disabled={disabled}
                  checkedChildren="是"
                  unCheckedChildren="否"
                  checked={text === 1 ? true : false}
                  onChange={(checked) => {
                    if (checked) {
                      setIsHaveContract(true);
                    } else {
                      setIsHaveContract(false);
                    }

                    let type = isShowListType;
                    setIsShowListType(0);
                    setTimeout(() => setIsShowListType(type));
                    contractForm?.setFieldValue('haveContract', checked ? 1 : 0);
                  }}
                />
              );
            },
          },
          {
            field: `purchaseApplyName`,
            label: `采购申请`,
            component: 'Input',
            disabled: disabled,
            placeholder: '请选择',
            // required: !isHaveContract,
            onClick: handleApplyPurchase,
            ishidden: isHaveContract,
            contentAfter:
              pageType == 'detail' ? null : (
                <a>
                  <SearchOutlined onClick={handleApplyPurchase} />
                </a>
              ),
          },
          {
            field: `purchaseFile`,
            label: `采购文件`,
            component: 'Render',
            // required: !isHaveContract,
            ishidden: isHaveContract,
            placeholder: '请上传',
            render: (text, record) => {
              const fileName = 'purchaseFile';
              return (
                <>
                  {!disabled ? (
                    <UploadFormCommon
                      form={contractForm}
                      fileFormName={fileName}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      required={false}
                      // accept={'.doc|.docx'}
                      url={'/assetInfo/uploadFile'}
                      downloadUrl={'/assetInfo/downloadFile'}
                      fileFormDelName={'delFile'}
                      delFunc={(delFilePath: string) => {
                        console.log('--- w文件url', delFilePath);
                      }}
                      // maxFile={1}
                      defaultFiles={text}
                      hintTitle={'且只能上传 1 个！'}
                      fieldBusiPath={'purchaseFile'}
                    >
                      上传
                    </UploadFormCommon>
                  ) : (
                    <div
                      style={{
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        marginLeft: '8px',
                      }}
                    >
                      {record?.[fileName]
                        ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                            return (
                              <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                                <a
                                  onClick={() => {
                                    message.success('下载中，请稍后...');
                                    downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                                  }}
                                >
                                  <MyIcon type="icon-file-text-fill" />
                                  &nbsp;
                                  {getFileNameNotType(e.attachName, 8)}
                                </a>
                              </Tooltip>
                            );
                          })
                        : '--'}
                    </div>
                  )}
                </>
              );
            },
          },
          {
            field: `contractName`,
            label: `采购合同`,
            component: 'Input',
            disabled: disabled,
            required: !isNoContract || isHaveContract,
            ishidden: !isHaveContract,
            placeholder: '请选择',
            onClick: handleSelectContract,
            contentAfter:
              pageType == 'detail' ? null : (
                <a>
                  <SearchOutlined onClick={handleSelectContract} />
                </a>
              ),
          },
          {
            field: `contractProcessName`,
            label: `履约节点`,
            component: 'Input',
            disabled: disabled,
            placeholder: '请选择',
            autoComplete: 'off',
            required: !isNoContract || isHaveContract,
            ishidden: !isHaveContract,
            onClick: handleContractProcess,
            contentAfter:
              pageType == 'detail' ? null : (
                <a>
                  <SearchOutlined onClick={handleContractProcess} />
                </a>
              ),
          },
          // {
          //   field: `storageTypes`,
          //   label: `验收类型`,
          //   component: 'Render',
          //   required: true,
          //   disabled: disabled,
          //   colSpan: 2,
          //   placeholder: '请选择',
          //   message:'请选择验收类型',
          //   render: (text) => {
          //     return (
          //       <TagSelect
          //         colSpan={24}
          //         formLabel={''}
          //         formName={'storageTypes'}
          //         defalultKeys={Number(text)}
          //         // onChange={(value) => setIsShowListType(value)}
          //         radioDisabled={disabled}
          //         radioList={[
          //           {
          //             value: 1,
          //             name: '到货验收',
          //           },
          //           {
          //             value: 2,
          //             name: '其他验收',
          //           },
          //           {
          //             value: 3,
          //             name: '到货验收&其他验收',
          //           },
          //         ]}
          //       />
          //     );
          //   },
          // },
          {
            field: `storageType`,
            label: `标的类型`,
            component: 'Render',
            required: true,
            disabled: disabled,
            colSpan: 2,
            placeholder: '请选择',
            render: (text) => {
              return (
                <TagSelect
                  colSpan={24}
                  formLabel={''}
                  formName={'storageType'}
                  defalultKeys={Number(text)}
                  onChange={(value) => {
                    setIsShowListType(value);
                  }}
                  radioDisabled={disabled}
                  radioList={[
                    {
                      value: 1,
                      name: '货物类',
                    },
                    {
                      value: 2,
                      name: '服务类',
                    },
                    {
                      value: 3,
                      name: '货物类&服务类',
                    },
                  ]}
                />
              );
            },
          },
          {
            field: `fileAll`,
            label: `文件资料是否齐全`,
            component: 'Render',
            required: true,
            disabled: disabled,
            placeholder: '请选择',
            render: (text) => {
              return (
                <Switch checkedChildren="是" unCheckedChildren="否" onChange={(value) => {}} disabled={disabled} checked={Boolean(text)} />
                // <TagSelect
                //   colSpan={24}
                //   formLabel={''}
                //   formName={'fileAll'}
                //   defalultKeys={Number(text)}
                //   onChange={() => {}}
                //   // radioDisabled={}
                //   radioList={[
                //     {
                //       value: 1,
                //       name: '是',
                //     },
                //     {
                //       value: 0,
                //       name: '否',
                //     },
                //   ]}
                // />
              );
            },
          },
          {
            field: `matarialAll`,
            label: `备品备件是否齐全`,
            component: 'Render',
            required: true,
            disabled: disabled,
            placeholder: '请选择',
            render: (text) => {
              return (
                <Switch checkedChildren="是" unCheckedChildren="否" onChange={(value) => {}} disabled={disabled} checked={Boolean(text)} />
                // <TagSelect
                //   colSpan={24}
                //   formLabel={''}
                //   formName={'matarialAll'}
                //   defalultKeys={Number(text)}
                //   onChange={() => { }}
                //   // radioDisabled={}
                //   radioList={[
                //     {
                //       value: 1,
                //       name: '是',
                //     },
                //     {
                //       value: 0,
                //       name: '否',
                //     },
                //   ]}
                // />
              );
            },
          },
          {
            field: `checkFlag`,
            label: `收货检验`,
            component: 'Render',
            required: true,
            disabled: disabled,
            placeholder: '请选择',
            colSpan: 2,
            render: (text) => {
              return (
                <TagSelect
                  colSpan={24}
                  formLabel={''}
                  formName={'checkFlag'}
                  defalultKeys={Number(text)}
                  onChange={() => {}}
                  radioDisabled={disabled}
                  radioList={[
                    {
                      value: 0,
                      name: '合格',
                    },
                    {
                      value: 1,
                      name: '存在一般问题，经现场处理解决',
                    },
                  ]}
                />
              );
            },
          },
          {
            field: `otherInfo`,
            label: `其他说明`,
            component: 'InputTextArea',
            disabled: disabled,
            placeholder: '请填写',
            required: false,
            colSpan: 2,
            allowClear: true,
            showCount: true,
            maxLength: 200,
            autoSize: { minRows: 2, maxRows: 4 },
          },
          {
            field: `applyFile`,
            label: `相关附件`,
            component: 'Render',
            required: isLineDown,
            placeholder: '请上传',
            colSpan: 2,
            render: (text, record) => {
              const fileName = 'applyFile';
              return (
                <>
                  {!disabled ? (
                    <UploadFormCommon
                      form={contractForm}
                      fileFormName={fileName}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      required={false}
                      // accept={'.doc|.docx'}
                      url={'/assetInfo/uploadFile'}
                      downloadUrl={'/assetInfo/downloadFile'}
                      fileFormDelName={'delFile'}
                      delFunc={(delFilePath: string) => {
                        console.log('--- w文件url', delFilePath);
                      }}
                      // maxFile={1}
                      defaultFiles={text}
                      hintTitle={'且只能上传 1 个！'}
                      fieldBusiPath={'assetFile'}
                    >
                      上传
                    </UploadFormCommon>
                  ) : (
                    <div
                      style={{
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        marginLeft: '8px',
                      }}
                    >
                      {record?.[fileName]
                        ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                            return (
                              <div>
                                <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                                  <a
                                    onClick={() => {
                                      message.success('下载中，请稍后...');
                                      downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                                    }}
                                  >
                                    <MyIcon type="icon-file-text-fill" />
                                    &nbsp;
                                    {getFileNameNotType(e.attachName, 8)}
                                  </a>
                                </Tooltip>
                                {/* 轻阅读预览 */}
                                <Tooltip title={'在线预览'}>
                                  <Button type="link" size="small" onClick={() => onOpenReadOfdWord(e?.attachUrl)} icon={<EyeOutlined />} />
                                </Tooltip>
                              </div>
                            );
                          })
                        : '--'}
                    </div>
                  )}
                </>
              );
            },
          },
        ],
      },
      // 合同信息
      // {
      //   key: 'accept-contract',
      //   title: '',
      //   fieldCustomDom: <UpdateContractView formName={contractForm} pageType={pageType} />,
      // },
      // 货物列表
      {
        key: 'accept-procurement',
        title: isShowListType == 3 || isShowListType == 1 ? '二、货物' : '',
        fieldCustomDom:
          isShowListType == 3 || isShowListType == 1 ? (
            <UpdateMaterielView
              addMaterialModalStatus={addMaterialModalStatus}
              editTable={editTable}
              isHaveContract={isHaveContract}
              openMaterialModalStatus={openMaterialModalStatus}
              formName={contractForm}
              pageType={pageType}
            />
          ) : null,
      },
      // 服务列表
      {
        key: 'accept-serviceList',
        title: isShowListType == 3 || isShowListType == 2 ? (isShowListType == 2 ? '二、服务' : '三、服务') : '',
        fieldCustomDom:
          isShowListType == 3 || isShowListType == 2 ? (
            <UpdateServiceView
              addMaterialModalStatus={addMaterialModalStatus}
              editTable={editTable}
              isHaveContract={isHaveContract}
              openMaterialModalStatus={openServerModalStatus}
              formName={contractForm}
              pageType={pageType}
            />
          ) : null,
      },
    ],
  });

  return {
    config,
    methods,
  };
};

export { getUpdateConfig };
